import router from '../../router/router'

let defaultPage = {
	name: 'index',
	tabname: '主页',
	path: '/index'
};

const state = {
	worktab: {
		list: [defaultPage],
		current: defaultPage
	},
	closingPage: ''
}

const mutations = {
	worktabRemove(state, p) {
		// 关闭标签
		let ind = state.worktab.list.findIndex(s => s.name === p)
		if (ind > -1) {
			// 清理 keep alive - start
			state.closingPage = state.worktab.list[ind].name
			// 清理 keep alive - end
			state.worktab.list.splice(ind, 1)
		}
		var index = state.worktab.list.length - 1;
		if (index === -1) {
			//如果是最后一个标签被关闭就打开默认
			state.worktab.list.push(defaultPage);
			state.worktab.current = defaultPage;
			router.push(defaultPage.path);
		} else {
			if (p === state.worktab.current.name) {
				// 是当前页，返回上一页
				var index = state.worktab.list.length - 1;
				router.push(state.worktab.list[index].path);
			}
		}

	},
	worktabRoute(state, p) {
		let ind = state.worktab.list.findIndex(s => s.name === p.to.name);
		if (ind > -1) {
			// 标签已存在
			state.worktab.current = state.worktab.list[ind]
		} else {
			// 标签不存在，现在新建
			if(p.to.name!==''){
				//过滤空标签
				state.worktab.list.push(p.to)
				state.worktab.current = p.to
			}
		}
		state.closingPage = ''
	}
}

const actions = {
	worktabRemove({commit}, p) {
		commit('worktabRemove', p)
	},
	worktabRoute({commit}, p) {
		commit('worktabRoute', p)
	}
}

export default {
	namespaced: true,
	state,
	actions,
	mutations
}



